<?php

namespace app\admin\validate;

use think\Validate;

/**
 * 管理员管理验证器
 */
class Admin extends Validate
{
    protected $failException = true;

    protected $rule = [
        'username'  => 'require|length:3,20|regex:^[a-zA-Z0-9_\x80-\xff\s·]+$|unique:admin',
        'nickname'  => 'require',
        'password'  => 'require|length:6,32|regex:^(?!.*[&<>"\'\n\r]).{6,32}$',
        'email'     => 'email|unique:admin',
        'mobile'    => 'mobile|require|unique:admin',
        'group_arr' => 'require|array',
    ];

    /**
     * 验证提示信息
     * @var array
     */
    protected $message = [];

    /**
     * 字段描述
     */
    protected $field = [];

    /**
     * 验证场景
     */
    protected $scene = [
        'add' => ['username', 'nickname', 'password', 'email', 'mobile', 'group_arr'],
    ];

    public function __construct()
    {
        $this->field   = [
            'username'  => '用户名',
            'nickname'  => '昵称',
            'password'  => '密码',
            'email'     => '邮箱',
            'mobile'    => '手机号',
            'group_arr' => '管理员分组',
            'status'    => '状态'
        ];
        $this->message = array_merge($this->message, [
            'username.regex'  => '请输入正确的用户名!',
            'username.length' => '用户名长度必须在3-20字符之间!',
            'password.length' => '密码长度必须在6-32字符之间!',
            'password.regex'  => '请输入正确的密码!'
        ]);
        parent::__construct();
    }

    /**
     * 验证场景-前台自己修改自己资料
     */
    public function sceneInfo(): Admin
    {
        return $this->only(['nickname', 'password', 'email', 'mobile'])
            ->remove('password', 'require');
    }

    /**
     * 验证场景-编辑资料
     */
    public function sceneEdit(): Admin
    {
        return $this->only(['username', 'nickname', 'password', 'email', 'mobile', 'group_arr'])
            ->remove('password', 'require');
    }

    /**
     * 验证场景-编辑基本资料
     */
    public function sceneBasicInfo(): Admin
    {
        return $this->only(['username', 'nickname', 'email', 'mobile']);
    }

    /**
     * 验证场景-修改管理员状态
     */
    public function sceneEditStatus(): Admin
    {
        return $this->only(['status'])->append('status', 'checkStatus');
    }

    /**
     * 管理员状态自定义验证规则
     * @param $value // 需验证的值
     * @param $rule // 验证规则
     * @param array $data // 数据
     */
    protected function checkStatus($value, $rule, array $data = [])
    {
        $status = (string)$data['status'] ?? ''; // 验证码
        if ($status === '') {
            return '修改失败！';
        } else if ($status !== '0' && $status !== '1') {
            return '修改失败！';
        }
        return true;
    }
}
